import { defineStore } from "pinia";

import { getUserInfo } from "@/request/apis/user.js";

import { switchPatient, getPatientList } from "@/request/apis/patient.js";

import { switchIm, initIm, updateBadge } from "@/utils/im";

export const useStore = defineStore({
  id: "myStore",
  state: () => ({
    patient: {
      current: null,
      list: [],
    },
    userInfo: null,
  }),
  actions: {
    switchPatient(patient: any) {
      if (patient) {
        this.patient.current = patient;
        // updateBadge(0)
        // switchPatient({
        // 	id: this.patient.current.id
        // }).then(() => {
        // 	this.refreshPatientList();
        // }).catch(() => {})
        // // 初始化IM
        // if (uni.$UIKitNIM) {
        // 	if (uni.getStorageSync("yxAccountId") != this.patient.current.wyyxAccId) {
        // 		switchIm(this.patient.current.wyyxAccId, this.patient.current.wyyxToken)
        // 	}
        // } else {
        // 	initIm(this.patient.current.wyyxAccId, this.patient.current.wyyxToken)
        // }
      } else {
        this.patient.current = null;
      }
    },
    getUserInfo() {
      getUserInfo().then((res) => {
        this.userInfo = res;
      });
    },
    setPatientInfo(info: object) {
      this.patient.current = info;
    },
    async initPatientList(patientId?: string) {
      const res = await getPatientList();
      if (res && res.records.length > 0) {
        this.patient.list = res.records;
        if (patientId) {
          let index = arrFindObjIndex(res.records, "id", patientId);
          if (index === -1) {
            this.switchPatient(res.records[0]);
          } else {
            this.switchPatient(res.records[index]);
          }
        } else {
          const index = arrFindObjIndex(res.records, "defaultPatient", 1);
          if (index == -1) {
            this.switchPatient(res.records[0]);
          } else {
            this.switchPatient(res.records[index]);
          }
        }
      } else {
        this.switchPatient(null);
        this.patient.list = [];
        // to do 是否需要销毁IM
      }
      function arrFindObjIndex(arr: any, key: any, val: any) {
        return arr.findIndex((item: any) => item[key] === val);
      }
    },
    refreshPatientList() {
      getPatientList()
        .then((res: any) => {
          if (res && res.length > 0) {
            this.patient.list = res;
          } else {
            this.switchPatient(null);
            this.patient.list = [];
          }
        })
        .catch(() => {
          this.switchPatient(null);
          this.patient.list = [];
        });
    },
  },
});
